const authService = require("../service/auth.server");
const { UNAUTHORIZATION, UNPERMISSION } = require("../constant");
const { publicKey } = require("../config/keys");
const jwt = require("jsonwebtoken");

//验证请求头是否携带token,token是否伪造
const verifyAuth = async (ctx, next) => {
  console.log("验证授权的middleware~");
  // 1.获取token
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    return ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
  const token = authorization.replace("Bearer ", "");

  // 2.验证token(id/name/iat/exp)
  try {
    const result = jwt.verify(token, publicKey, {
      algorithms: ["RS256"],
    });
    ctx.user = result;
    await next();
  } catch (err) {
    console.log(err, "authMiddleware");
    ctx.app.emit("error", UNAUTHORIZATION, ctx);
  }
};

// 验证操作人是否是当前用户
const verifyPermission = async (ctx, next) => {
  const [resourceKey] = Object.keys(ctx.params);
  const tableName = resourceKey.replace("Id", "");
  const resourceId = ctx.params[resourceKey];
  const { id } = ctx.user;

  // 2.查询是否具备权限
  try {
    const isPermission = await authService.checkResource(tableName, resourceId, id);
    if (!isPermission) {
      return ctx.app.emit("error", UNPERMISSION, ctx);
    }
    await next();
  } catch (err) {
    return ctx.app.emit("error", UNPERMISSION, ctx);
  }
};

module.exports = { verifyAuth, verifyPermission };
